package com.zr.inquiry.service.impl;

import com.sun.corba.se.spi.ior.iiop.IIOPProfileTemplate;
import com.sun.org.apache.regexp.internal.RE;
import com.zr.inquiry.mapper.InquiryMapper;
import com.zr.inquiry.model.*;
import com.zr.inquiry.model.vo.*;
import com.zr.inquiry.service.InquiryService;
import com.zr.legalperson.model.LegalPerson;
import com.zr.util.AllRecords;
import com.zr.util.ResultVO;
import com.zr.util.ResultVOBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2019/1/7.
 */
@Service
public class InquiryServiceImpl implements InquiryService{

    @Autowired
    private InquiryMapper inquiryMapper;
    @Override
    public ResultVO<List<Supplier>> getSupplierName(Integer legalPersonId) {
        List<Supplier> supplierName = inquiryMapper.getSupplierName(legalPersonId);
        System.out.println(supplierName);
        return ResultVOBuilder.success(supplierName);
    }

    @Override
    public ResultVO<AllRecords> selectMaterial(SelectMaterialVo selectMaterialVo) {
        int count = inquiryMapper.queryCount(selectMaterialVo);
        List<SelectMaterial> selectMaterials = inquiryMapper.queryPage(selectMaterialVo);
        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(selectMaterials);
        allRecords.setPageIndex(selectMaterialVo.getPageIndex());
        allRecords.setPageSize(selectMaterialVo.getPageSize());
        allRecords.resetTotalNumber(count);
        allRecords.setTotalNumber(count);
        return ResultVOBuilder.success(allRecords);
    }

    @Override
    public ResultVO<AllRecords> searchPartnerPage(SupplierSelectVo supplierSelectVo) {
        int count = inquiryMapper.querySupplierCount(supplierSelectVo);
        List<Supplier> selectMaterials = inquiryMapper.querySupplierPage(supplierSelectVo);
        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(selectMaterials);
        allRecords.setPageIndex(supplierSelectVo.getPageIndex());
        allRecords.setPageSize(supplierSelectVo.getPageSize());
        allRecords.resetTotalNumber(count);
        allRecords.setTotalNumber(count);
        return ResultVOBuilder.success(allRecords);
    }

    @Override
    public ResultVO<List<InquiryAddVo>> addInquiry(InquiryAddVo inquiryAddVo) {
        //验证有效开始时间是否在当前时间之前。
        //验证有效结束时间是否在有效开始时间之前。



       /* ResultVO resultVO = validateCreateTimeAndEndTime(inquiryAddVo);
        if (resultVO.getErrorCode()!=null){
            return ResultVOBuilder.error("500",resultVO.getErrorMessage());
        }*/



        //效验询价数量是否大于0
        
        //验证备件明细是否重复--提示存在重复，重复的备件为***
        ResultVO resultVO1 = validateSpareRepeat(inquiryAddVo.getInquiryDetailsList(),inquiryAddVo.getSupplierDetailsList());
        if (!resultVO1.isSuccess()){
            return ResultVOBuilder.error(resultVO1.getErrorMessage(),"500");
        }
        //验证供应商明细是否重复 --提示存在重复，重复的供应商为***
//        inquiryMapper.validateSupplierRepeat();
        //验证备件是否存在合法的供应商  ---需要到中间表去获取关联信息，进行验证
        //int i = inquiryMapper.validateSpareIsLeage(inquiryAddVo.getInquiryDetailsList());
        //验证供应商下是否存在合法的备件 ---需要到中间表去获取关联信息，进行验证
//        inquiryMapper.validateSupplierIsLeage();
        Date date = new Date();
        InquiryTotal inquiryTotal = new InquiryTotal();
        BeanUtils.copyProperties(inquiryAddVo,inquiryTotal);
        inquiryTotal.setCreateId(1024);
        inquiryTotal.setCreateName("小明");
        inquiryTotal.setCreateTime(date);
        inquiryTotal.setStartTime(date);
        String uuid = UUID.randomUUID().toString();
        inquiryTotal.setRequestForQuotationId(uuid);
        //入库

        //1.1插入主表信息，返回插入的id
        inquiryMapper.insertInquiryTotal(inquiryTotal);
        System.out.println(inquiryTotal.getId());

        //1.2给备件明细中的外键id赋值，随后插入备件数据。
        List<InquirySpareVo> list = new ArrayList<>();
        List<Spare> spares = new ArrayList<>();
        list = inquiryAddVo.getInquiryDetailsList();
        for (InquirySpareVo inquirySpare:list){
            Spare spare = new Spare();
            BeanUtils.copyProperties(inquirySpare,spare);
            spare.setRequestForQuotationId(uuid);
            spares.add(spare);
        }
        inquiryMapper.insertInquirySpareDetials(spares);

        //3.给供应商明细中的外键id赋值，随后插入供应商表数据。
        List<InquirySupplierVo> inquirySupplierVos = new ArrayList<>();
        List<Supplier> supplierList = new ArrayList<>();
        inquirySupplierVos = inquiryAddVo.getSupplierDetailsList();
        for (InquirySupplierVo inquirySupplierVo:inquirySupplierVos){
            Supplier supplier = new Supplier();
            BeanUtils.copyProperties(inquirySupplierVo,supplier);
            supplier.setRequestForQuotationId(uuid);
            supplierList.add(supplier);
        }
        inquiryMapper.insertInquirySupplierDetails(supplierList);
        List<InquiryAddVo> inquiryAddVo1 = new ArrayList<>();
        return ResultVOBuilder.success(inquiryAddVo1);
    }

    @Override
    public ResultVO<AllRecords> inquiryQueryPage(InquiryListSelectVo inquiryListSelectVo) {
        int count = inquiryMapper.queryInquiryCount(inquiryListSelectVo);
        List<InquiryListSelectResultVo> listSelectResultVos = inquiryMapper.queryInquiryPage(inquiryListSelectVo);

        for (InquiryListSelectResultVo in:listSelectResultVos){
            if (in.getInquiryStatus()==10){
                in.setInquiryStatusName(EnumInquiryStatus.getName(1));
            }
            if (in.getInquiryStatus()==20){
                in.setInquiryStatusName(EnumInquiryStatus.getName(2));
            }
            if (in.getInquiryStatus()==30){
                in.setInquiryStatusName(EnumInquiryStatus.getName(0));
            }
            if (in.getInquiryStatus()==40){
                in.setInquiryStatusName(EnumInquiryStatus.getName(3));
            }
            if (in.getInquiryStatus()==50){
                in.setInquiryStatusName(EnumInquiryStatus.getName(4));
            }
        }
        AllRecords allRecords = new AllRecords();
        allRecords.setPageSize(inquiryListSelectVo.getPageSize());
        allRecords.setTotalNumber(count);
        allRecords.resetTotalNumber(count);
        allRecords.setPageIndex(inquiryListSelectVo.getPageIndex());
        allRecords.setDataList(listSelectResultVos);

        return ResultVOBuilder.success(allRecords);
    }

    //回显
    @Override
    public ResultVO inquirySheetSee(InquirySeeVo inquirySeeVo) {

        List<InquirySeeVo> inquirySeeVoList = new ArrayList<>();
        InquirySeeVo inquirySeeVos = inquiryMapper.inquirySheetSee(inquirySeeVo.getRequestForQuotationId());
        System.out.println(inquirySeeVos);
        //给询价类型赋值
        for (int i = 0; i < EnumInquiryType.values().length; i++){
            if (inquirySeeVos.getType() == i){
                inquirySeeVos.setTypeName(EnumInquiryType.getName(i));
            }
        }

       //是否含税赋值
        for (int i = 0; i < EnumInquiryIsTax.values().length; i++){
            if (inquirySeeVos.getIsTax()==i){
                inquirySeeVos.setIsTaxName(EnumInquiryType.getName(i));
            }
        }
        //给币别赋值
        for (int i = 0; i < EnumInquiryCurrency.values().length;i++){
            if (inquirySeeVos.getCurrencyCode()==i){
                inquirySeeVos.setCurrencyCodeWord(EnumInquiryCurrency.getName(i));
            }
        }

        //给备件明细和供应商明细赋值
        List<InquirySpareVo> inquirySpareVo = inquiryMapper.queryInquirySpareDetails(inquirySeeVo.getRequestForQuotationId());
        System.out.println(inquirySpareVo);
        List<InquirySupplierVo> inquirySupplierVo = inquiryMapper.queryInquirySupplierDetails(inquirySeeVo.getRequestForQuotationId());
        System.out.println(inquirySupplierVo);

        List<InquirySpareVo> inquirySpareVos = new ArrayList<>();
        List<InquirySupplierVo> inquirySupplierVos = new ArrayList<>();

        inquirySeeVos.setInquiryDetailsList(inquirySpareVo);
        inquirySeeVos.setSupplierDetailsList(inquirySupplierVo);

        inquirySeeVoList.add(inquirySeeVos);
        System.out.println(inquirySeeVoList);
        return ResultVOBuilder.success(inquirySeeVoList);
    }

    @Override
    @Transactional
    public ResultVO<InquiryUpdateVo> inquiryUpdateByRequestForQuotationId(@Valid InquiryUpdateVo inquiryUpdateVo) {

        InquiryTotal inquiryTotal =  inquiryMapper.queryInquiryByRfqid(inquiryUpdateVo.getRequestForQuotationId());
        if (inquiryTotal==null){
            return ResultVOBuilder.error("500","您修改的物件不存在");
        }
        List<InquirySpareVo> inquiryDetailsList = inquiryUpdateVo.getInquiryDetailsList();
        List<InquirySupplierVo> supplierDetailsList = inquiryUpdateVo.getSupplierDetailsList();
        //验重
        ResultVO resultVO = validateUpdateInquiry(inquiryDetailsList,supplierDetailsList);
        if (!resultVO.isSuccess()){
            return ResultVOBuilder.error(resultVO.getErrorCode(),resultVO.getErrorMessage());
        }
        //验证备件与供应商之间是否相互合法：备件有没有对应得供应商，供应商有无对应得备件
        ResultVO isLeagelVo = validateSpareAndSupplierIsLeagel(inquiryDetailsList,supplierDetailsList);
        if (!isLeagelVo.isSuccess()){
            return ResultVOBuilder.error(isLeagelVo.getErrorCode(),isLeagelVo.getErrorMessage());
        }
        //判断询价日期和结束日期是否在当前时间之前
        InquiryUpdateVo inquiryUpdateVo1 = new InquiryUpdateVo();
        BeanUtils.copyProperties(inquiryUpdateVo,inquiryUpdateVo1);
        ResultVO chechTime = ckeckStartTimeAndEndTime(inquiryUpdateVo1);
        if (!chechTime.isSuccess()){
            return ResultVOBuilder.error(chechTime.getErrorCode(),chechTime.getErrorMessage());
        }
        //修改表头信息
        BeanUtils.copyProperties(inquiryUpdateVo,inquiryTotal);
        inquiryTotal.setCreateId(inquiryUpdateVo.getCreatorId());
        inquiryTotal.setCreateTime(inquiryUpdateVo.getCreateTime());
        inquiryTotal.setLegalPersonId(inquiryUpdateVo.getLegalPersonId());
        inquiryMapper.updateInquiryTotal(inquiryTotal);

        //集合先删除，在添加
        inquiryMapper.deleteInquirySpare(inquiryUpdateVo.getRequestForQuotationId());
        inquiryMapper.deleteInquirySupplier(inquiryUpdateVo.getRequestForQuotationId());

        List<Spare> spareList = new ArrayList<>();
        for (InquirySpareVo in: inquiryDetailsList){
            Spare spare = new Spare();
            BeanUtils.copyProperties(in,spare);
            spare.setRequestForQuotationId(inquiryUpdateVo.getRequestForQuotationId());
            spareList.add(spare);
        }
        inquiryMapper.insertInquirySpareDetials(spareList);

        List<Supplier> supplierList = new ArrayList<>();
        for (InquirySupplierVo supplierVo:supplierDetailsList){
            Supplier supplier = new Supplier();
            BeanUtils.copyProperties(supplierVo,supplier);
            supplier.setRequestForQuotationId(inquiryUpdateVo.getRequestForQuotationId());
            supplierList.add(supplier);
        }
        inquiryMapper.insertInquirySupplierDetails(supplierList);
        System.out.println(inquiryUpdateVo);
        return ResultVOBuilder.success(inquiryUpdateVo);
    }

    /**
     * 审核
     * @param inquiryUpdateVo
     * @return
     */
    @Override
    public ResultVO inquiryUpdateShenke(@Valid InquiryUpdateShenheStatusVo inquiryUpdateVo) {
        InquiryTotal inquiryTotal = inquiryMapper.queryInquiryByRfqid(inquiryUpdateVo.getRequestForQuotationId());
        if (inquiryTotal==null){
            return ResultVOBuilder.error("404","你要审核的订单不存在,请重新选择");
        }

        if (inquiryUpdateVo.getAuditorStatus()==1){
            //状态为1，去数据库改为深刻状态
            inquiryTotal.setInquiryStatus(30);
            inquiryMapper.updateStatusShenhe(inquiryTotal);
        }else{
            inquiryTotal.setInquiryStatus(10);
            inquiryMapper.updateStatusShenheToSave(inquiryTotal);
        }
        return ResultVOBuilder.success(inquiryUpdateVo);
    }

    @Override
    public ResultVO inquiryUpdateShenPi(@Valid InquiryUpdateShenPiStatusVo inquiryUpdateVo) {
        InquiryTotal inquiryTotal = inquiryMapper.queryInquiryByRfqid(inquiryUpdateVo.getRequestForQuotationId());
        if (inquiryTotal==null){
            return ResultVOBuilder.error("404","你要审批的订单不存在,请重新选择");
        }
        if(inquiryUpdateVo.getApproverStatus()==1){
            inquiryTotal.setInquiryStatus(40);
            inquiryMapper.updateStatusShenhe(inquiryTotal);
        }else {
            inquiryTotal.setInquiryStatus(50);
            inquiryMapper.updateStatusShenheToSave(inquiryTotal);
        }
        return ResultVOBuilder.success(inquiryUpdateVo);
    }

    @Override
    public ResultVO inquiryUpdateZuofei(@Valid InquiryUpdateZuofeiVo inquiryUpdateVo) {
        InquiryTotal inquiryTotal = inquiryMapper.queryInquiryByRfqid(inquiryUpdateVo.getRequestForQuotationId());
        if (inquiryTotal==null){
            return ResultVOBuilder.error("404","你要审批的订单不存在,请重新选择");
        }
            inquiryTotal.setInquiryStatus(inquiryUpdateVo.getOrderStatus());
            inquiryMapper.updateStatusShenhe(inquiryTotal);

        return ResultVOBuilder.success(inquiryUpdateVo);
    }

    private ResultVO ckeckStartTimeAndEndTime(InquiryUpdateVo inquiryUpdateVo1) {
        Date date = new Date();
        //判断询价开始时间是否在当前时间之前

        if (date.before(inquiryUpdateVo1.getStartTime())){
            return ResultVOBuilder.error("500","询价开始时间在当前时间之前");
        }
        if (date.after(inquiryUpdateVo1.getEndTime())){
            return ResultVOBuilder.error("500","询价结束日期在当前时间之后");
        }
        return ResultVOBuilder.success(inquiryUpdateVo1);
    }

    private ResultVO validateSpareAndSupplierIsLeagel(List<InquirySpareVo> inquiryDetailsList, List<InquirySupplierVo> supplierDetailsList) {

        List<String> clientSpareCode = new ArrayList<>();
        List<String> clientSupplierCode = new ArrayList<>();


        for (InquirySpareVo in:inquiryDetailsList){
            clientSpareCode.add(in.getSpareCoding());
        }
        for (InquirySupplierVo in:supplierDetailsList){
            clientSupplierCode.add(in.getVendorCode());
        }
        //通过前端传的code，到数据库中得到对象的备件和供应商
        List<String> serverSupplierCode = inquiryMapper.querySpareBySpareCoding(clientSpareCode);
        List<String> serverSpareCode = inquiryMapper.querySupplierBySupplierCoding(clientSupplierCode);

        if (!serverSpareCode.containsAll(clientSpareCode)){
            clientSupplierCode.removeAll(serverSupplierCode);
            if (clientSpareCode.size()>0){
                return ResultVOBuilder.error("500","有供应商"+clientSupplierCode.toString()+"没找到对应的备件");
            }

        }

        if (!serverSupplierCode.containsAll(clientSupplierCode)){
            clientSpareCode.removeAll(serverSpareCode);
            if (clientSupplierCode.size()>0){
                return ResultVOBuilder.error("500","有备件"+clientSpareCode.toString()+"没有对应的供应商");
            }
        }
        return ResultVOBuilder.success("ok");

    }

    private ResultVO validateUpdateInquiry(List<InquirySpareVo> inquiryDetailsList, List<InquirySupplierVo> supplierDetailsList) {
        //验证备件明细是否重复 --提示存在重复，重复的备件为***
        List<String> spareCodeList = new ArrayList<>();
        List<String> errorCodeList = new ArrayList<>();

        for (InquirySpareVo in : inquiryDetailsList){
            if (!spareCodeList.contains(in.getSpareCoding())){
                spareCodeList.add(in.getSpareCoding());
            }else
            {
                errorCodeList.add(in.getSpareCoding());
            }
        }
        if (!CollectionUtils.isEmpty(errorCodeList)){
            return ResultVOBuilder.error("500",errorCodeList+"这些供应商编码重复，请重新输入");
        }
        //验证供应商明细是否重复 --提示存在重复，重复的供应商为***
        List<String> supplierCodeList = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        for (InquirySupplierVo in:supplierDetailsList){
            if (!supplierCodeList.contains(in.getVendorCode())){
                supplierCodeList.add(in.getVendorCode());
            }else{
                errorList.add(in.getVendorCode());
            }
        }
        if(!CollectionUtils.isEmpty(errorList)){
            return ResultVOBuilder.error("500",errorList+"这些备件重复，请重新选择");
        }
        return ResultVOBuilder.success("ok");
    }

    //验证备件和供应商是否合法
    private ResultVO validateSpareRepeat(List<InquirySpareVo> inquiryDetailsList, List<InquirySupplierVo> supplierDetailsList) {
        //1.先将接收的备件集合：inquiryDetailsVoList集合中的编码属性提取出来储存在集合中:inquiryDetailsCodeList
        List<String> inquiryDetailsCodeList = new ArrayList<>();
        List<String> errorCodeList = new ArrayList<>();
        for (InquirySpareVo in: inquiryDetailsList){
            String spareCoding = in.getSpareCoding();
            //判断是否重复
            if (inquiryDetailsCodeList.contains(spareCoding)){
                errorCodeList.add(spareCoding);
            }else {
                inquiryDetailsCodeList.add(in.getSpareCoding());
            }
        }
        //如果错误集合里面不是空，则给前端提示错误信息
        if (!CollectionUtils.isEmpty(errorCodeList)){
            return  ResultVOBuilder.error("500",errorCodeList+"重复，请重新选择");
        }
        //2.supplierDetailsCodeList是符合要求的
        List<String> supplierDetailsCodeList = new ArrayList<>();
        for (InquirySupplierVo su: supplierDetailsList){
            String vendorCode = su.getVendorCode();
            if (supplierDetailsCodeList.contains(vendorCode)){
                return ResultVOBuilder.error("500",vendorCode+"重复，请重修选择");
            }else {
                supplierDetailsCodeList.add(su.getVendorCode());
            }
        }
        //3.根据备件inquiryDetailsCodeList集合查询供应商集合的编码：querySupplierDetailsCodeList
        List<String> supplierCodeList = inquiryMapper.querySupplierByDetailsCodeList(inquiryDetailsCodeList);
        //4.根据供应商supplierDetailsCodeList查询备件的编码集合 querySpareBySupplierCode
        List<String> spareCodeList = inquiryMapper.querySpareBySupplierCode(supplierDetailsCodeList);

        //5.判断集合备件集合：queryInquiryDetailsCodeList，是否包含供应商集合：inquiryDetailsCodeList
        boolean b = spareCodeList.containsAll(inquiryDetailsCodeList);
        if (!b){
        //查找是哪个备件没有对应的供应商
        inquiryDetailsCodeList.removeAll(spareCodeList);
        if(inquiryDetailsCodeList.size()>0){
            return ResultVOBuilder.error("有备件:"+inquiryDetailsCodeList.get(0)+"没有找到对应的生产商","500");
        }else{
            return ResultVOBuilder.error("有备件没有找到对应的生产商","500");
        }

    }
    //6.判断集合备件集合：querySupplierDetailsCodeList，是否包含供应商集合：supplierDetailsCodeList
    boolean b1 = supplierCodeList.containsAll(supplierDetailsCodeList);
        if (!b1){
        //查找是哪个供应商没有对应的备件
        supplierDetailsCodeList.removeAll(inquiryDetailsCodeList);
        if (supplierDetailsCodeList.size()>0){
            return ResultVOBuilder.error("有生产商:"+supplierDetailsCodeList.get(0)+"没有可以生产的商品","500");
        }else {
            return ResultVOBuilder.error("有生产商没有可以生产的商品","500");
        }

    }

        return ResultVOBuilder.success("");
    }
    private ResultVO validateCreateTimeAndEndTime(InquiryAddVo inquiryAddVo) {
        Date date = new Date();
        if (!date.before(inquiryAddVo.getStartTime())){
            return ResultVOBuilder.error("500","询价开始日期在当前时间之前");
        }
        if (!date.after(inquiryAddVo.getEndTime())){
            return ResultVOBuilder.error("500","询价开始日期在当前时间之后");
        }
        return ResultVOBuilder.success("ok");
    }
}
